﻿using System;
using Microsoft.Phone.Controls;
using Coding4Fun.MissionControl.WP.Misc;
using Coding4Fun.MissionControl.WP.ViewModels;

namespace Coding4Fun.MissionControl.WP.Views
{
    public partial class LearnCodePage : PhoneApplicationPage
    {
        public LearnCodePage()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            AttemptLearnCode();
        }

        private async void AttemptLearnCode()
        {
            if (!string.IsNullOrWhiteSpace(txtName.Text))
            {
                CommonViewModel.Instance.IsWaiting = true;
                this.Focus();

                bool commandSent = await CommonViewModel.Instance.CommandClient.SendCommand(CommonViewModel.Instance.CurrentServer.Location,
                    string.Format(Constants.COMMAND_LEARN_NEW, CommonViewModel.Instance.CurrentSet), txtName.Text);
                if (!commandSent)
                {
                    Alert.Send(Constants.MESSAGE_SERVER_CONNECT_FAIL);
                }
                else
                {
                    Alert.Send(Constants.MESSAGE_COMMAND_LEARN_WAIT);
                    NavigationService.GoBack();
                }

                CommonViewModel.Instance.IsWaiting = false;
            }
            else
            {
                Alert.Send(Constants.MESSAGE_NO_NAME_FAIL);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        private void txtName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
                AttemptLearnCode();
        }

        private void WaitingOverlayLayoutUpdated(object sender, EventArgs e)
        {
            if (grdConnectOverlay.Visibility == System.Windows.Visibility.Collapsed)
            {
                ApplicationBar.IsVisible = true;
            }
            else
            {
                ApplicationBar.IsVisible = false;
            }
        }
    }
}